<?php
/**
 * 管理员类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 18-12-21
 * Time: 下午12:20
 */
namespace app\common\model;

use com\Hash;
use think\Db;

class Admin
{
    private const TABLE_NAME                = 'admin';
    private const TABLE_HIERARCHY           = 'hierarchy';
    private const TABLE_ADMIN_HIERARCHY     = 'admin_hierarchy';

    /**
     * 根据用户名查询用户信息
     * @author 王海东
     * @date
     * @param string $name  用户名
     * @return array
     * @throws \Exception
     */
    public function getAdminByName(string $name = '')
    :array {
        try {
            $data = Db::name(self::TABLE_NAME)
              ->field('id,name,pwd,tel,admin_id,hierarchy_id')
              ->where('name',$name)
              ->whereNull('delete_time')
              ->find() ?? [];
        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }

        return $data;
    }

    /**
     * 检查是否存在
     * @author 王海东
     * @param int    $type  1,检查用户名;2,检查电话;
     * @param string $value 要检查的值
     * @return bool 是否已存在
     * @throws
     */
    public function checkExits(int $type, string $value)
    : bool {

        if ($type === 1) {
            $field = "name";
        } elseif ($type === 2) {
            $field = "tel";
        } else {
            throw new \Exception("要检查的类型错误");
        }

        try {
            return Db::name(self::TABLE_NAME)
                     ->field("id")
                     ->where($field, $value)
                     ->find() ? true : false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除管理员
     * @author 王海东
     * @date
     * @param int $id   管理员id
     * @return bool
     * @throws \Exception
     */
    public function delete(int $id)
    :bool {
        try {
            return Db::name(self::TABLE_NAME)
              ->where('id',$id)
              ->setField('delete_time',date('Y-m-d H:i:s')) ? true :false;
        } catch (\Exception $e) {
            throw new \Exception('删除失败');
        }
    }

    /**
     * 新增管理员
     * @author 王海东
     * @date
     * @param string $name  用户名
     * @param string $pwd   密码
     * @param int    $tel   手机号
     * @param int    $hierarchy_id      平台层级id
     * @param int    $admin_id          管理员层级id
     * @return int
     * @throws \Exception
     */
    public function add(string $name,string $pwd,int $tel,int $hierarchy_id,int $admin_id)
    : int{

        $pwd = Hash::pwd($pwd);

        $insert = [
                'name'          => $name,
                'pwd'           => $pwd,
                'tel'           => $tel,
                'hierarchy_id'  => $hierarchy_id,
                'admin_id'      => $admin_id,
                'code'          => create_invite_code(6),
                'create_time'   => date('Y-m-d H:i:s')
            ];

        try {
            $id = Db::name(self::TABLE_NAME)
                    ->insertGetId($insert);
        } catch (\Exception $e) {
            throw new \Exception('新增失败');
        }

        return $id;
    }

    /**
     * 修改管理员密码
     * @author 王海东
     * @date
     * @param int   $id     管理员id
     * @param string $pwd    密码
     * @return bool
     * @throws \Exception
     */
    public function editPwd(int $id,string $pwd)
    :bool {

        $pwd = Hash::pwd($pwd);

        try {
            return Db::name(self::TABLE_NAME)
              ->where('id',$id)
              ->setField('pwd',$pwd) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('修改失败');
        }
    }

    /**
     * 管理员详细信息
     * @author 王海东
     * @date
     * @param int $id   管理员id
     * @return array
     * @throws \Exception
     */
    public function info(int $id)
    :array {
        try {
            $data = Db::name(self::TABLE_NAME)
              ->field('id,name,tel,code,create_time,admin_id,hierarchy_id')
              ->where('id',$id)
              ->whereNull('delete_time')
              ->find() ?? [];
        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }

        return $data;
    }

    /**
     * 根据邀请码获取管理员id
     * @author 王海东
     * @date
     * @param string $code  推广码
     * @return int
     * @throws \Exception
     */
    public function getIdByCode(string $code)
    :int {
        try {
            $id = Db::name(self::TABLE_NAME)
                      ->where('code',$code)
                      ->whereNull('delete_time')
                      ->value('id') ?? '';

            return $id;
        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }
    }

    /**
     * 根据管理员编号获取相关id集
     * @author 王海东
     * @date
     * @param int $id   管理员id
     * @return array
     * @throws \Exception
     */
    public function getIds(int $id)
    :array {
        $info = $this->info($id);

        if(!$info) {
            return [];
        }

        $ah     = new AdminHierarchy();
        $list   = $ah->getIds($info['admin_id']);

        $ids = Db::name(self::TABLE_NAME)
            ->where('admin_id','in',$list)
            ->column('id') ?? [];

        return $ids;
    }

    /**
     * 查询管理员列表
     * @author 王海东
     * @date
     * @param int   $id         用户编号
     * @param int   $page       页码
     * @param int   $pageSize   页幅
     * @param array $where      检索条件 [name|用户名或手机号，agent_name|代理商名称，start_time,end_time|注册时间]
     * @return array
     * @throws \Exception
     */
    public function select(int $id,int $page,int $pageSize,array $where = [])
    :array {

        $db = Db::name(self::TABLE_NAME)->alias('a');

        $db->join(self::TABLE_HIERARCHY.' h','a.hierarchy_id = h.id','left');
        $db->join(self::TABLE_ADMIN_HIERARCHY.' ah','a.admin_id = ah.id','left');

        if(isset($where['name'])) {
            $db->where('a.name|a.tel',$where['name']);
        }

        if(isset($where['start_time'])) {
            $db->where('a.create_time','>=',$where['start_time']);
        }

        if(isset($where['end_time'])) {
            $db->where('a.create_time','<=',$where['end_time']);
        }

        $db->whereNull('a.delete_time');


        $data = $this->getIds($id);

        if(isset($where['agent_name'])) {

            $agent = $this->getAdminByName($where['agent_name']);

            if($agent) {
                $admin_id = $agent['id'];
                if(!in_array($admin_id,$data)) {
                    $admin_id = 0;
                }
            } else {
                $admin_id = 0;
            }
            $data = $this->getIds($admin_id);
        }


        $list = [];
        foreach ($data as $key => $val) {
            if($val != $id) {
                array_push($list,$val);
            }
        }

        $db->where('a.id','in',$list);


        $count = $db->count('a.id');

        if($count <= 0) {
            return [
                'count' => 0,
                'list'  => []
            ];
        }

        try {
            $result = $db->field([
                'a.id',
                'a.name',
                'a.tel',
                'a.code',
                'a.create_time',
                'h.title',
                'ah.pid'
            ])
                 ->order('a.create_time desc')
                 ->page($page,$pageSize)
                 ->select();

            $subjection = Db::name(self::TABLE_NAME)
                      ->column('admin_id,name');

            foreach ($result as &$val) {
                $val['subjection'] = $subjection[$val['pid']];
            }

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return [
            'count' => $count,
            'list'  => $result
        ];
    }

    /**
     * 以id作为下标获取所有管理员名称
     * @author 王海东
     * @date
     * @return array
     */
    public function getAdmin()
    :array {
        return Db::name(self::TABLE_NAME)
                 ->column('id,name,hierarchy_id');
    }
}